<template>
  <div v-loading="loading" class="app-container">
    <el-button v-if="checkPermission(permissionRoles.role_add)" type="primary" @click="handleAddRole">创建角色</el-button>

    <el-table :data="rolesList" border class="mt-15" height="770">
      <el-table-column align="center" label="编号(id)" width="220">
        <template slot-scope="scope">
          {{ scope.$index+1 }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="角色标识" width="220">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="角色名" width="220">
        <template slot-scope="scope">
          {{ scope.row.title }}
        </template>
      </el-table-column>
      <el-table-column align="header-center" label="描述">
        <template slot-scope="scope">
          {{ scope.row.remark }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button v-if="checkPermission(permissionRoles.role_edit)" type="text" size="small" @click="handleEdit(scope)">编辑</el-button>
          <el-button v-if="checkPermission(permissionRoles.role_del)" type="text" size="small" @click="handleDelete(scope)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑角色':'创建角色'" :close-on-click-modal="false">
      <el-form ref="role" :rules="rules" :model="role" label-width="80px" label-position="left">
        <el-form-item label="角色标识" prop="name">
          <el-input v-model="role.name" placeholder="填写角色标识" />
        </el-form-item>
        <el-form-item label="角色名" prop="title">
          <el-input v-model="role.title" placeholder="填写角色名" />
        </el-form-item>
        <el-form-item label="描述" prop="remark">
          <el-input
            v-model="role.remark"
            :autosize="{ minRows: 2, maxRows: 4}"
            type="textarea"
            placeholder="填写角色描述"
          />
        </el-form-item>
        <el-form-item label="菜单">
          <el-tree
            ref="tree"
            :check-strictly="checkStrictly"
            :data="routesData"
            :props="defaultProps"
            show-checkbox
            node-key="path"
            class="permission-tree"
          />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmRole">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import path from 'path'
import { deepClone } from '@/utils'
import checkPermission from '@/utils/permission' // 权限判断函数
import { getRoutes, getRoles, addRole, deleteRole, updateRole } from '@/api/role'

const defaultRole = {
  id: '',
  name: '',
  title: '',
  remark: '',
  routes: [],
  permission: []
}

export default {
  data() {
    return {
      permissionRoles: this.$store.state.user.permissionRoles,
      loading: false,
      role: Object.assign({}, defaultRole),
      routes: [],
      rolesList: [],
      dialogVisible: false,
      dialogType: 'new',
      checkStrictly: false,
      isIndeterminate: true,
      checkAll: false,
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      rules: {
        name: [{ required: true, message: '请填写角色标识', trigger: 'blur' }],
        title: [{ required: true, message: '请选择角色名称', trigger: 'blur' }],
        remark: [{ required: true, message: '请填写角色描述', trigger: 'blur' }]
      }
    }
  },
  computed: {
    routesData() {
      return this.routes
    }
  },
  created() {
    this.getRoutes()
    this.getRoles()
  },
  methods: {
    checkPermission,
    async getRoutes() {
      const res = await getRoutes()
      this.serviceRoutes = res.data
      this.routes = this.generateRoutes(res.data)
    },
    async getRoles() {
      this.loading = true
      const res = await getRoles()
      this.loading = false
      this.rolesList = res.data
    },
    // 重塑routes结构，使其看起来与侧边栏相同
    generateRoutes(routes, basePath = '/') {
      const res = []

      for (let route of routes) {
        // 跳过隐藏路由
        // if (route.hidden) { continue }

        const onlyOneShowingChild = this.onlyOneShowingChild(route.children, route)

        if (route.children && onlyOneShowingChild && !route.alwaysShow) {
          route = onlyOneShowingChild
        }

        const data = {
          path: path.resolve(basePath, route.path),
          title: route.meta && route.meta.title

        }

        // 递归子路由
        if (route.children) {
          data.children = this.generateRoutes(route.children, data.path)
        }
        res.push(data)
      }
      return res
    },
    generateArr(routes) {
      let data = []
      routes.forEach(route => {
        data.push(route)
        if (route.children) {
          const temp = this.generateArr(route.children)
          if (temp.length > 0) {
            data = [...data, ...temp]
          }
        }
      })
      return data
    },
    handleAddRole() {
      this.role = Object.assign({}, defaultRole)
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedNodes([])
      }
      this.dialogType = 'new'
      this.dialogVisible = true
      this.isIndeterminate = true
    },
    handleEdit(scope) {
      // this.handleCheckedChange(scope.row.permission)
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.checkStrictly = true
      this.role = deepClone(scope.row)
      this.$nextTick(() => {
        const routes = this.generateRoutes(this.role.routes)
        this.$refs.tree.setCheckedNodes(this.generateArr(routes))
        // 设置节点的选中状态不影响其父节点和子节点
        this.checkStrictly = false
      })
    },
    handleDelete({ $index, row }) {
      this.$confirm('你确定要删除此角色[ ' + row.title + ' ]吗?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await deleteRole(row.id)
          this.rolesList.splice($index, 1)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(err => { console.error(err) })
    },
    generateTree(routes, basePath = '/', checkedKeys) {
      const res = []
      for (const route of routes) {
        const routePath = path.resolve(basePath, route.path)

        // 递归子路由
        if (route.children) {
          route.children = this.generateTree(route.children, routePath, checkedKeys)
        }

        if (checkedKeys.includes(routePath) || (route.children && route.children.length >= 1)) {
          // 把按钮放到权限
          if (route.type === 3) this.role.permission.push(route.path)
          res.push(route)
        }
      }
      return res
    },
    async confirmRole() {
      this.role.permission = ['admin']
      this.$refs['role'].validate((valid) => {
        if (valid) {
          const isEdit = this.dialogType === 'edit'

          const checkedKeys = this.$refs.tree.getCheckedKeys()
          this.role.routes = this.generateTree(deepClone(this.serviceRoutes), '/', checkedKeys)

          if (isEdit) {
            updateRole(this.role.id, this.role)
            for (let index = 0; index < this.rolesList.length; index++) {
              if (this.rolesList[index].id === this.role.id) {
                this.rolesList.splice(index, 1, Object.assign({}, this.role))
                break
              }
            }
          } else {
            addRole(this.role).then(response => {
              this.role.id = response.data.id
              this.rolesList.push(this.role)
            }).catch(err => {
              this.$message.error(err)
            })
          }

          this.dialogVisible = false
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
        }
      })
    },
    // 参考: src/view/layout/components/Sidebar/SidebarItem.vue
    onlyOneShowingChild(children = [], parent) {
      let onlyOneChild = null
      const showingChildren = children.filter(item => !item.hidden)

      // 当只有一个子路由时，默认情况下显示子路由 (不需要)
      // if (showingChildren.length === 1) {
      //   onlyOneChild = showingChildren[0]
      //   onlyOneChild.path = path.resolve(parent.path, onlyOneChild.path)
      //   return onlyOneChild
      // }

      // 如果没有要显示的子路由，则显示父路由
      if (showingChildren.length === 0) {
        onlyOneChild = { ... parent, path: '', noShowingChildren: true }
        return onlyOneChild
      }

      return false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>
